package com.jfs.exception;


import com.jfs.result.Result;
import com.jfs.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description 全局异常处理器
 * @E-mail cwm3412638@163.com
 * @Author cwm
 * @Date 2022/7/25
 */
@RestControllerAdvice
@Slf4j
public class ExceptionAdviceHandler {

    /**
     * 未知异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> unKnowExceptionHandler(Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.failed(e.getMessage());
    }

    /**
     * 用户名或密码错误异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BadCredentialsException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> badCredentialsExceptionHandler(BadCredentialsException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.failed(ResultCode.USERNAME_OR_PASSWORD_ERROR);
    }

    /**
     * 用户不存在异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = UsernameNotFoundException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> usernameNotFoundExceptionHandler(UsernameNotFoundException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.failed(ResultCode.USER_NOT_EXIST);
    }

    /**
     * 权限不足异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = ForbiddenException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> usernameNotFoundExceptionHandler(ForbiddenException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.failed(ResultCode.USER_NOT_EXIST);
    }

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Object> constraintViolationExceptionHandler(MethodArgumentNotValidException e){
        log.error(e.getMessage());
        e.printStackTrace();
        return Result.failed(ResultCode.METHOD_ARGUMENT_NOT_VALID.getCode(),e.getFieldError().getDefaultMessage());
    }
}

